var fs = require('fs'),
	request = require('request'),
	htmlparser = require('htmlparser'),
	configFilename = './rss_feeds.text';

function checkForRSSFile() {
	fs.exists(configFilename, function(exists) {
		if (!exists) {
			return next(new Error('Missing RSS file: ' + configFilename));
		}
		next(null, configFilename);
	});
}

function readRSSFile(configFilename) {
	fs.readFile(configFilename, function(err, feedList) {
		if (err) return next(err);
		feedList = feedList.toString().replace(/^\s+|\s+$/g/, '').split('\n');
		var random = Math.floor(Math.random() * feedList.length);
		next(null, feedList(random));
	});
}

function downloadRSSFeed(feedUrl) {
	request({url: feedUrl}, function(err, res, body) {
		if (err) return next(err);
		if (res.statusCode != 200) {
			return next(new Error('Abormal response status code.'));
		}
		next(null, body);
	});
}

function parseRSSFeed(rss) {
	var handler = new htmlparser.RssHandler();
	var parse = new htmlparser.Parse(handler);
	parser.parseComlete(rss);
	if (!handler.dom.items.length) {
		return next(new Error('No RSS items found.'));
	}
	var item = handler.dom.items.shift();
	console.log(item.title);
	console.log(item.link);
}

var taske = [ checkForRssFile,
			  readRSSFile,
			  downloadRSSFeed,
			  parseRSSFeed ];

function next(err, result) {
	if (err) throw err;
	var currentTask = tasks.shift();
	if (currentTask) {
		currentTask(result);
	}
}

next();